package com.yl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yl.dao.AppCategoryDao;
import com.yl.entity.AppCategoryEntity;
import com.yl.service.AppCategoryService;
import com.yl.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AppCategoryServiceImpl extends ServiceImpl<AppCategoryDao, AppCategoryEntity> implements AppCategoryService {
    @Override
    @Transactional
    public R addCategory(AppCategoryEntity appCategoryEntity) {
        if(!StrUtil.isEmpty(appCategoryEntity.getCategoryName())){
            LambdaQueryWrapper<AppCategoryEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AppCategoryEntity::getCategoryName, appCategoryEntity.getCategoryName());
            AppCategoryEntity one = this.getOne(wrapper);
            if(one != null){
                return R.error("分类名称已存在、不可重复添加!");
            }
            boolean flag = this.save(appCategoryEntity);
            if(flag){
                return R.ok("分类添加成功!");
            }
            return R.error("分类添加失败!");
        }
        return R.error("分类名称不能为空!");
    }

    @Override
    @Transactional
    public R deleteCategory(Long id) {
        boolean flag = this.removeById(id);
        if(flag){
            return R.ok("分类删除成功!");
        }
        return R.error("分类删除失败!");
    }

    @Override
    @Transactional
    public R updateCategory(AppCategoryEntity appCategoryEntity) {
        boolean flag = this.updateById(appCategoryEntity);
        if(flag){
            return R.ok("修改分类成功!");
        }
        return R.error("修改分类失败!");
    }

    @Override
    public IPage<AppCategoryEntity> getCategoryList(AppCategoryEntity appCategoryEntity) {
        LambdaQueryWrapper<AppCategoryEntity> wrapper = new LambdaQueryWrapper<>();
        if(!StrUtil.isEmpty(appCategoryEntity.getCategoryName())) {
            wrapper.eq(AppCategoryEntity::getCategoryName, appCategoryEntity.getCategoryName());
        }
        Page<AppCategoryEntity> page = this.page(new Page<>(appCategoryEntity.getPageIndex(), appCategoryEntity.getPageSize()), wrapper);
        return page;
    }
}
